import { ref } from 'vue';
import type { Product } from '../data/mockProducts';

export interface CartItem extends Product {
  quantity: number;
}

export const useCart = () => {
  const cartItems = ref<CartItem[]>([]);
  const cartVisible = ref(false);
  const cartTrigger = ref(false);
  const animatingItems = ref<number[]>([]);

  const addToCart = (product: Product) => {
    const existingItem = cartItems.value.find(item => item.id === product.id);

    if (existingItem) {
      existingItem.quantity += 1;
    } else {
      cartItems.value.push({ ...product, quantity: 1 });
    }

    // 触发动画
    animatingItems.value.push(product.id);
    setTimeout(() => {
      const index = animatingItems.value.indexOf(product.id);
      if (index > -1) {
        animatingItems.value.splice(index, 1);
      }
    }, 1000);

    cartTrigger.value = !cartTrigger.value;
  };

  const removeFromCart = (id: number) => {
    cartItems.value = cartItems.value.filter(item => item.id !== id);
  };

  const updateQuantity = (id: number, quantity: number) => {
    if (quantity < 1) return;
    const item = cartItems.value.find(item => item.id === id);
    if (item) item.quantity = quantity;
  };

  const totalItems = computed(() =>
    cartItems.value.reduce((total, item) => total + item.quantity, 0)
  );

  const totalPrice = computed(() =>
    cartItems.value.reduce((total, item) => total + item.price * item.quantity, 0)
  );

  const toggleCart = () => {
    cartVisible.value = !cartVisible.value;
  };

  return {
    cartItems,
    cartVisible,
    cartTrigger,
    animatingItems,
    addToCart,
    removeFromCart,
    updateQuantity,
    totalItems,
    totalPrice,
    toggleCart
  };
};